package com.ai3d.rfid.common.event

import android.database.sqlite.SQLiteConstraintException
import com.ai3d.rfid.common.log.Logcat
import com.ai3d.rfid.network.proxy.NetworkProxy
import com.bj.ski.base.database.AppDatabaseSingleton
import com.bj.ski.base.database.EventReq
import com.blankj.utilcode.util.GsonUtils
import com.ym521.logdog.LogDog
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import java.util.concurrent.atomic.AtomicBoolean

/**
 * @ProjectName : disc
 * @Author : weijinsong
 * @Time : 2023/7/6 22:35
 * @Description : 文件描述
 */
object EventMgs {
    private const val TAG = "EventMgs"
    const val KEY_EVENT_STORAGE = "key_event_storage"
    val lock = 1
    var max = 100

    /**
     * 保存缓存数据
     */

    fun putCache(eventReq: EventReq) {
        GlobalScope.launch(Dispatchers.IO) {
        synchronized(EventMgs::class.java) {
                try {
                    LogDog.debug(TAG, "putCache开始写入本地")
                    var result= AppDatabaseSingleton.getDatabase().eventMsgDao().insertEventReq(eventReq)
                    LogDog.debug(TAG, "putCache开始写入完成:${result}")
                }catch (e: SQLiteConstraintException){
                    LogDog.debug(TAG, "${e.message}插入数据失败:"+GsonUtils.toJson(eventReq))
                }

            }
        }
    }




    /**
     * 获取缓存数据
     **/




    /**
     * 实时上传，针对单个Event
     */
//    fun realEventReport(eventReq: EventReq) {
//        var eventReqs = LinkedList<EventReq>()
//        eventReqs.add(eventReq)
//        realEventReport(eventReqs)
//    }

    /**
     * 实时上传，针对单个Event list
     */
//    fun realEventReport(eventReqs: LinkedList<EventReq>) {
//        GlobalScope.launch(Dispatchers.IO) {
//            runCatching {
//                NetworkProxy.accountApi.event(eventReqs)
//            }.onSuccess {
//                if (it.code == 0) {//上报成功
//                    Logcat.d(TAG, "realEventReport 上报完成 it : ${it.code}")
//                } else {
//                    putCache(eventReqs)
//                    Logcat.d(TAG, "realEventReport 上报失败")
//                }
//            }.onFailure {
//                putCache(eventReqs)
//                Logcat.d(TAG, "realEventReport 上报失败")
//            }
//        }
//    }

    private val isUploading = AtomicBoolean(false)

    /**
     * 实时上传，针对cache缓存中的数据
     * TODO 可以测试一下并发情况
     */
    fun realEventReport() {
        LogDog.debug("realEventReport", "是否正在上传:" + isUploading)
        if (isUploading.get()) {
            return
        }
        if (isUploading.compareAndSet(false, true)) {
            GlobalScope.launch(Dispatchers.IO) {
                try {
                    val events = AppDatabaseSingleton.getDatabase().eventMsgDao().getRecentData()
                    if (events?.isEmpty() == true) {//为空不上传，直接中断
                        LogDog.debug("realEventReport", "本地缓存为空:不继续上报")
                    } else {
                        runCatching {
                            LogDog.debug(
                                "realEventReport",
                                "传入接口前上报内容:" + GsonUtils.toJson(events)
                            )
                            events?.forEach {
                                if (it?.userId?.isEmpty() == true) {
                                    LogDog.debug(
                                        "realEventReport",
                                        "上报了空userid" + GsonUtils.toJson(it)
                                    )
                                }
                            }
                            Logcat.d(TAG, "realEventReport events : ${events?.size}")
                            NetworkProxy.accountApi.event(events)
                        }.onSuccess {
                            if (it.code == 200) {//上报成功
                                removeSuccess(events)
                            } else {
                                Logcat.d(TAG, "realEventReport 上报失败")
                                LogDog.debug(
                                    "realEventReport",
                                    " ${it.code}上报失败:" + GsonUtils.toJson(events)
                                )
                            }
                        }.onFailure {
                            Logcat.d(TAG, "realEventReport 上报失败")
                            LogDog.debug(
                                "realEventReport",
                                " ${it.message}上报失败:" + GsonUtils.toJson(events)
                            )
                        }
                    }
                }catch (e:Exception){
                    LogDog.debug(
                        "realEventReport",
                        " ${e.message}上报失败:")
                }finally {
                    LogDog.debug("realEventReport", "isUploading设置为false")
                    isUploading.set(false)
                }

            }
        }
    }

    fun removeSuccess(
        events: List<EventReq>?
    ) {
        synchronized(EventMgs::class.java) {
            try {
                LogDog.debug("realEventReport", "上报成功")
                if (events != null) {
                    AppDatabaseSingleton.getDatabase().eventMsgDao().deleteEventReq(events)
                    LogDog.debug("realEventReport", "删除上报成功的数据")
                }
                var tempData = AppDatabaseSingleton.getDatabase().eventMsgDao().getAllData()
                if (null != tempData) {
                    LogDog.debug("realEventReport", "剩余未上报" + GsonUtils.toJson(tempData))
                }
            }catch (e: SQLiteConstraintException) {
                LogDog.debug("realEventReport", "删除数据失败")
            }
        }
    }
}